//
//  BWFDiscorverItemTitelView.swift
//  网易新闻项目
//
//  Created by 薄文飞 on 16/3/2.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class BWFDiscorverItemTitelView: UIView {

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        textFiledWidth = frame.size.width
        
        self.addSubview(cancelBtn)
        self.addSubview(textFiled)

        textFiled.addTarget(self, action: "showCancelBtn", forControlEvents: .EditingDidBegin)
        cancelBtn.addTarget(self, action: "hidenCancelBtn", forControlEvents: .TouchUpInside)
    }

    //自定义View
    //创建一个TextFiled
    let textFiled = UITextField()
    let cancelBtn = UIButton()
    
    let cancelWidth = 50
    var textFiledWidth :CGFloat = 0
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()

        //设置取消按钮的属性
        cancelBtn.frame = CGRect(x: self.bounds.size.width - CGFloat(cancelWidth) , y:0, width: CGFloat(cancelWidth), height: self.frame.size.height)
        cancelBtn.setTitle("取消", forState: .Normal)
        
        cancelBtn.setTitleColor(UIColor.blueColor(), forState: .Normal)
        
        //设置textFiled的属性
        textFiled.frame = self.bounds
        textFiled.backgroundColor = UIColor.greenColor()
        textFiled.frame.size.width = textFiledWidth

        textFiled.layer.borderWidth = 2
        textFiled.layer.borderColor = UIColor.blueColor().CGColor
        textFiled.layer.cornerRadius = 5
    
        leftImage.frame = CGRectMake(0, 0, frame.height, frame.height)
        leftImage.contentMode = .Center
        textFiled.leftView = leftImage
        textFiled.leftViewMode = .Always
        

    }

    func showCancelBtn() {
    
        textFiledWidth = self.bounds.size.width - CGFloat(cancelWidth)
        
        UIView.animateWithDuration(0.5) { () -> Void in
            
            self.textFiled.frame.size.width = self.textFiledWidth
        }
    }
    
    func hidenCancelBtn() {
    
        textFiledWidth = self.bounds.size.width
        
        UIView.animateWithDuration(0.5) { () -> Void in
            
            self.textFiled.frame.size.width = self.textFiledWidth
        }
        textFiled.resignFirstResponder()
    }
    
    private lazy var leftImage :UIImageView = {
        
        return UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))

    }()
    
}
